<template>
  <div class="webview-container">
    <!-- <div class="webview-header">
      <div class="header-info">
        <h3>会议室 - {{ roomName }}</h3>
        <div class="data-status" v-if="meeting?.title || user?.name || hasToken">
          <span v-if="meeting?.title" class="meeting-info">{{ meeting.title }}</span>
          <span v-if="user?.name" class="user-info">用户: {{ user.name }}</span>
          <span v-if="hasToken" class="token-info">🔐 已认证</span>
          <span v-else class="token-warning">⚠️ 未认证</span>
        </div>
      </div>
      <div class="controls">
        <el-button @click="requestMediaPermissions" type="warning" size="small">
          <CameraIcon style="margin-right: 4px" />
          获取权限
        </el-button>
        <el-button @click="resendData" type="info" size="small">
          发送数据
        </el-button>
        <el-button @click="refreshWebview" type="primary" size="small">刷新</el-button>
        <el-button @click="openInNewTab" type="success" size="small">新窗口打开</el-button>
        <el-button @click="closeWebview" type="danger" size="small">关闭</el-button>
      </div>
    </div> -->
    <div class="webview-content">
      <iframe
        ref="webviewFrame"
        :src="meetingUrl"
        frameborder="0"
        class="webview-iframe"
        allow="camera *; microphone *; display-capture *; fullscreen *; autoplay *; encrypted-media *; picture-in-picture *; screen-wake-lock *; web-share *"
        allowfullscreen
        @load="onIframeLoad"
      ></iframe>
    </div>
    <div v-if="loading" class="loading-overlay">
      <el-loading element-loading-text="正在加载会议室..."></el-loading>
    </div>
    
    <!-- 权限提示 -->
    <!-- <div class="permission-notice">
      <el-alert
        title="媒体权限提示"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          如果遇到摄像头或麦克风无法使用的问题，请点击"获取权限"按钮并允许浏览器访问您的设备。
          <span v-if="!hasToken" style="color: #d97706; font-weight: 500;">
            ⚠️ 未检测到认证token，会议功能可能受限。
          </span>
        </template>
      </el-alert>
    </div> -->
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElButton, ElMessage, ElAlert } from 'element-plus'
import { Camera as CameraIcon } from '@element-plus/icons-vue'
import { getToken } from '@/utils/webStorage'

// Props
const props = defineProps({
  room: {
    type: String,
    default: 'test-room'
  },
  baseUrl: {
    type: String,
    default: window.config_global.MEETING_BASE_URL || 'http://localhost:3000'
  },
  meeting: {
    type: Object,
    default: () => ({})
  },
  user: {
    type: Object,
    default: () => ({})
  }
})

// Reactive data
const webviewFrame = ref(null)
const loading = ref(true)

// 录屏相关状态
const screenRecorder = ref(null)
const screenStream = ref(null)
const recordedChunks = ref([])
const isRecording = ref(false)

// Computed
const meetingUrl = computed(() => {
  const params = new URLSearchParams()
  
  // 基础房间参数
  params.set('room', props.room || 'test-room')
  
  // 添加Token认证
  const token = getToken()
  if (token) {
    params.set('token', token)
    params.set('authorization', `Bearer ${token}`)
  }
  
  // 会议数据
  if (props.meeting && Object.keys(props.meeting).length > 0) {
    // 传递关键会议信息
    if (props.meeting.id) params.set('meetingId', props.meeting.id)
    if (props.meeting.title) params.set('meetingTitle', props.meeting.title)
    if (props.meeting.startTime) params.set('startTime', props.meeting.startTime)
    if (props.meeting.durationMinutes) params.set('duration', props.meeting.durationMinutes.toString())
    if (props.meeting.status) params.set('status', props.meeting.status)
    
    // 将完整会议数据作为JSON传递（Base64编码）
    try {
      const meetingData = JSON.stringify(props.meeting)
      params.set('meetingData', btoa(encodeURIComponent(meetingData)))
    } catch (error) {
      console.warn('会议数据编码失败:', error)
    }
  }
  
  // 用户数据
  if (props.user && Object.keys(props.user).length > 0) {
    // 传递关键用户信息
    if (props.user.uid) params.set('userId', props.user.uid.toString())
    if (props.user.username) params.set('userName', props.user.username)
    if (props.user.avatar) params.set('userAvatar', props.user.avatar)
    if (props.user.email) params.set('userEmail', props.user.email)
    
    // 将完整用户数据作为JSON传递（Base64编码）
    try {
      const userData = JSON.stringify({
        id: props.user.id,
        name: props.user.name,
        avatar: props.user.avatar,
        email: props.user.email,
        role: props.user.role || 'participant'
      })
      params.set('userData', btoa(encodeURIComponent(userData)))
    } catch (error) {
      console.warn('用户数据编码失败:', error)
    }
  }
  
  return `${props.baseUrl}/meeting?${params.toString()}`
})

const roomName = computed(() => {
  return props.room || 'test-room'
})

const hasToken = computed(() => {
  const token = getToken()
  return token && token.trim().length > 10 // 确保token不只是占位符
})

// Methods
const refreshWebview = () => {
  loading.value = true
  if (webviewFrame.value) {
    webviewFrame.value.src = meetingUrl.value
  }
  ElMessage.success('正在刷新会议室...')
}

// 监听来自iframe的postMessage消息
const handlePostMessage = (event) => {
  // 验证消息来源
  if (event.origin !== props.baseUrl && event.origin !== '*') {
    console.warn('收到来自未知来源的消息:', event.origin)
    return
  }
  
  try {
    const { type, action, data } = event.data
    
    console.log('收到iframe消息:', { type, data })
    
    // 处理关闭窗口消息
    if (type === 'close-window') {
      console.log('用户主动离开会议:', data?.message || '未知原因')
      ElMessage.info(data?.message || '用户已离开会议')
      closeWebview()
    }
    
    // 处理录屏消息
    if (type === 'recording') {
      const { data: recordingData } = data || {}
      console.log('收到录屏指令:', { action, data: recordingData })
      
      if (action === 'start') {
        startScreenRecording(recordingData)
      } else if (action === 'stop') {
        stopScreenRecording(recordingData)
      }
    }
    
    // 可以在这里添加其他消息类型的处理
    // 例如：type === 'meeting-started', type === 'meeting-ended' 等
    
  } catch (error) {
    console.error('处理iframe消息失败:', error)
  }
}

// 检查媒体权限
const checkMediaPermissions = async () => {
  try {
    // 检查摄像头权限
    const cameraPermission = await navigator.permissions.query({ name: 'camera' })
    const microphonePermission = await navigator.permissions.query({ name: 'microphone' })
    
    console.log('摄像头权限状态:', cameraPermission.state)
    console.log('麦克风权限状态:', microphonePermission.state)
    
    if (cameraPermission.state === 'denied' || microphonePermission.state === 'denied') {
      ElMessage.warning('检测到摄像头或麦克风权限被拒绝，会议功能可能受限')
      return false
    }
    
    return true
  } catch (error) {
    console.log('权限检查失败:', error)
    return true // 如果检查失败，继续加载
  }
}

// 请求媒体权限
const requestMediaPermissions = async () => {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ 
      video: true, 
      audio: true 
    })
    // 立即停止流，我们只是为了获取权限
    stream.getTracks().forEach(track => track.stop())
    ElMessage.success('摄像头和麦克风权限已获取')
    return true
  } catch (error) {
    console.error('获取媒体权限失败:', error)
    ElMessage.error('无法获取摄像头或麦克风权限，请在浏览器设置中允许访问')
    return false
  }
}

const openInNewTab = () => {
  window.open(meetingUrl.value, '_blank')
  ElMessage.info('已在新窗口打开会议室')
}

const closeWebview = () => {
  // 如果正在录屏，先停止录屏
  if (isRecording.value) {
    stopScreenRecording()
  }
  
  // 可以发出事件让父组件处理
  emit('close')
  ElMessage.info('会议室已关闭')
}

// 开始屏幕录制
const startScreenRecording = async (recordingData = {}) => {
  if (isRecording.value) {
    ElMessage.warning('录屏已在进行中')
    return
  }
  
  try {
    // 请求屏幕共享权限
    const stream = await navigator.mediaDevices.getDisplayMedia({ 
      video: {
        cursor: 'always',
        displaySurface: 'monitor'
      }, 
      audio: {
        echoCancellation: true,
        noiseSuppression: true,
        sampleRate: 44100
      }
    })
    
    screenStream.value = stream
    recordedChunks.value = []
    isRecording.value = true
    
    // 创建录制器
    const recorder = new MediaRecorder(stream, {
      mimeType: 'video/webm;codecs=vp9'
    })
    screenRecorder.value = recorder
    
    // 监听数据可用事件
    recorder.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
      }
    }
    
    // 监听录制停止事件
    recorder.onstop = () => {
      if (recordedChunks.value.length > 0) {
        // 生成录制文件
        const blob = new Blob(recordedChunks.value, { 
          type: 'video/webm' 
        })
        
        // 创建下载链接
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = generateFileName(recordingData)
        a.style.display = 'none'
        
        // 添加到页面并触发下载
        document.body.appendChild(a)
        a.click()
        
        // 清理
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
        
        ElMessage.success('录屏已完成，文件已下载到本地')
      }
      
      // 重置状态
      isRecording.value = false
      screenRecorder.value = null
      screenStream.value = null
      recordedChunks.value = []
    }
    
    // 监听录制错误
    recorder.onerror = (event) => {
      console.error('录屏错误:', event)
      ElMessage.error('录屏过程中发生错误')
      stopScreenRecording()
    }
    
    // 开始录制
    recorder.start(1000) // 每秒保存一次数据
    ElMessage.success('屏幕录制已开始')
    
    // 监听流结束事件（用户停止共享）
    stream.getVideoTracks()[0].onended = () => {
      if (isRecording.value) {
        ElMessage.info('用户停止了屏幕共享，录屏已结束')
        stopScreenRecording()
      }
    }
    
  } catch (error) {
    console.error('开始录屏失败:', error)
    if (error.name === 'NotAllowedError') {
      ElMessage.error('用户拒绝了屏幕共享权限')
    } else if (error.name === 'NotFoundError') {
      ElMessage.error('未找到可用的屏幕或窗口')
    } else {
      ElMessage.error('无法开始屏幕录制: ' + error.msg)
    }
    isRecording.value = false
  }
}

// 停止屏幕录制
const stopScreenRecording = (recordingData = {}) => {
  if (!isRecording.value || !screenRecorder.value) {
    ElMessage.warning('没有正在进行的录屏')
    return
  }
  
  try {
    // 停止录制器
    if (screenRecorder.value.state !== 'inactive') {
      screenRecorder.value.stop()
    }
    
    // 停止所有媒体流
    if (screenStream.value) {
      screenStream.value.getTracks().forEach(track => {
        track.stop()
      })
    }
    
    ElMessage.info('正在处理录屏文件...')
    
  } catch (error) {
    console.error('停止录屏失败:', error)
    ElMessage.error('停止录屏时发生错误')
    
    // 强制重置状态
    isRecording.value = false
    screenRecorder.value = null
    screenStream.value = null
    recordedChunks.value = []
  }
}

// 生成文件名
const generateFileName = (recordingData = {}) => {
  const now = new Date()
  const dateStr = now.toISOString().slice(0, 19).replace(/:/g, '-')
  const roomName = recordingData.roomName || props.room || 'meeting'
  const userName = recordingData.userInfo?.name || recordingData.userInfo?.username || 'user'
  
  return `录屏_${roomName}_${userName}_${dateStr}.webm`
}

const onIframeLoad = async () => {
  loading.value = false
  ElMessage.success('会议室加载完成')
  
  // 向iframe发送数据
  setTimeout(() => {
    sendDataToIframe()
  }, 1000) // 延迟1秒确保iframe完全加载
  
  // 再次检查权限状态
  setTimeout(async () => {
    const hasPermissions = await checkMediaPermissions()
    if (!hasPermissions) {
      ElMessage({
        message: '提示：如果无法使用摄像头或麦克风，请点击"获取权限"按钮',
        type: 'warning',
        duration: 5000
      })
    }
  }, 2000) // 延迟2秒再检查，让iframe有时间加载
}

// 向iframe发送数据
const sendDataToIframe = () => {
  if (!webviewFrame.value || !webviewFrame.value.contentWindow) {
    console.warn('iframe未准备好，无法发送数据')
    return
  }
  
  try {
    const token = getToken()
    
    const messageData = {
      type: 'MEETING_DATA',
      timestamp: Date.now(),
      payload: {
        meeting: props.meeting || {},
        user: props.user || {},
        room: props.room || 'test-room',
        token: token || null,
        authorization: token ? `Bearer ${token}` : null,
        permissions: {
          camera: true,
          microphone: true,
          screen: true
        }
      }
    }
    
    console.log('向iframe发送数据:', {
      ...messageData,
      payload: {
        ...messageData.payload,
        token: messageData.payload.token ? `已包含 (长度: ${messageData.payload.token.length})` : '未包含'
      }
    })
    
    // 发送到iframe
    webviewFrame.value.contentWindow.postMessage(
      messageData,
      props.baseUrl || '*'
    )
    
    ElMessage.success('数据已发送到会议室')
  } catch (error) {
    console.error('发送数据到iframe失败:', error)
    // ElMessage.warning('数据传输可能不完整')
  }
}

// 手动发送数据到iframe
const resendData = () => {
  sendDataToIframe()
  ElMessage.info('正在重新发送数据...')
}

// Emits
const emit = defineEmits(['close'])

// Lifecycle
onMounted(async () => {
  const token = getToken()
  console.log('WebView组件已挂载，正在加载:', meetingUrl.value)
  console.log('接收到的会议数据:', props.meeting)
  console.log('接收到的用户数据:', props.user)
  console.log('当前Token状态:', token ? '已获取' : '未获取', token ? `(长度: ${token.length})` : '')
  
  // 检查媒体权限
  await checkMediaPermissions()
  
  // 添加postMessage监听器
  window.addEventListener('message', handlePostMessage)
})

// 组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('message', handlePostMessage)
  
  // 如果正在录屏，停止录屏
  if (isRecording.value) {
    stopScreenRecording()
  }
})
</script>

<style scoped>
.webview-container {
  width: 100%;
  height: 75vh;
  /* max-height: 600px; */
  min-height: 400px;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.webview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
}

.header-info {
  flex: 1;
  min-width: 0;
}

.webview-header h3 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
  font-weight: 500;
}

.data-status {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.meeting-info, .user-info {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(37, 99, 235, 0.1);
  color: #2563eb;
  font-weight: 500;
}

.token-info {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(34, 197, 94, 0.1);
  color: #059669;
  font-weight: 500;
}

.token-warning {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(245, 158, 11, 0.1);
  color: #d97706;
  font-weight: 500;
}

.controls {
  display: flex;
  gap: 8px;
}

.webview-content {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.webview-iframe {
  width: 100%;
  height: 100%;
  border: none;
  display: block;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10;
}

.permission-notice {
  position: absolute;
  bottom: 20px;
  left: 20px;
  right: 20px;
  z-index: 20;
}

.permission-notice .el-alert {
  border-radius: 8px;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .webview-container {
    height: 70vh;
    max-height: 500px;
    min-height: 350px;
  }

  .webview-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
    padding: 8px 12px;
  }
  
  .controls {
    width: 100%;
    justify-content: space-between;
    flex-wrap: wrap;
  }
  
  .permission-notice {
    bottom: 10px;
    left: 10px;
    right: 10px;
  }
}
</style>
